package com.my.study.controller;

import com.my.study.entity.BookEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;

/**
 * @author Carlos
 * @version 1.0
 * @Description 常用请求参数注解的使用
 * @date 2021/11/13 18:49
 **/
@Controller
@RequestMapping("/parameter")
public class ParameterTestController {

    private final static Logger LOGGER = LoggerFactory.getLogger(ParameterTestController.class);


    @ResponseBody
    @GetMapping("/pathVariable/{id}/owner/{userName}")
    public Object pathVariable(@PathVariable("id") Long id,
                               @PathVariable("userName") String userName,
                               @PathVariable Map<String, String> pvMap,
                               @RequestHeader("User-Agent") String userAgent,
                               @RequestHeader Map<String, String> headers) {
        LOGGER.info("id:{}, userName:{}", id, userName);
        LOGGER.info("pbMap: {}", pvMap);
        LOGGER.info("userAgent: {}", userAgent);
        LOGGER.info("headers: {}", headers);
        Map<String, Object> map = new HashMap<>(8);

        map.put("id", id);
        map.put("userName", userName);
        map.put("pvMap", pvMap);
        map.put("userAgent", userAgent);
        map.put("headers", headers);

        return map;
    }


    @ResponseBody
    @RequestMapping("/requestHeader")
    public Object requestHeader(@RequestHeader("User-Agent") String userAgent,
                                @RequestHeader Map<String, String> headers) {
        LOGGER.info("userAgent: {}", userAgent);
        LOGGER.info("headers: {}", headers);
        Map<String, Object> map = new HashMap<>(8);

        map.put("userAgent", userAgent);
        map.put("headers", headers);

        return map;
    }


    @ResponseBody
    @RequestMapping("/requestParam")
    public Object requestParam(@RequestParam("age") Integer age,
                               @RequestParam("inters") List<String> inters,
                               @RequestParam Map<String, String> params) {
        LOGGER.info("age: {}", age);
        LOGGER.info("inters: {}", inters);
        LOGGER.info("params: {}", params);
        Map<String, Object> map = new HashMap<>(8);

        map.put("age", age);
        map.put("inters", inters);
        map.put("params", params);

        return map;
    }


    /**
     * <p>
     * 矩阵变量语法：/matrixVariable;param1=123;param2=qaz,wsx,edc
     *
     * <p>
     * SpringBoot中默认是不开启矩阵变量的功能，需要手动开启。
     * 原理：
     * 查看 WebMvcAutoConfiguration -> UrlPathHelper.removeSemicolonContent属性
     *
     * @param path
     * @param param1
     * @param param2
     * @param variable
     * @return Object
     */
    @ResponseBody
    @RequestMapping("/matrixVariable/{path}")
    public Object matrixVariable(@PathVariable("path") String path, //仅仅是请求的路径，不包含矩阵变量
                                 @MatrixVariable("param1") String param1,
                                 @MatrixVariable("param2") List<String> param2,
                                 @MatrixVariable Map<String, String> variable) {
        Map<String, Object> map = new HashMap<>(8);

        map.put("path", path);
        map.put("param1", param1);
        map.put("param2", param2);
        map.put("variable", variable);

        return map;
    }


    @GetMapping("forwardSuccess")
    public String forwardSuccess(Map<String,Object> map,
                                 Model model,
                                 HttpServletRequest request,
                                 HttpServletResponse response) {
        map.put("map", "map作用域");
        model.addAttribute("model", "model作用域");
        request.setAttribute("request", "request");

        Cookie cookie = new Cookie("c1", "v1");
        response.addCookie(cookie);


        return "forward:success";
    }


    @ResponseBody
    @GetMapping("/success")
    public Object success(HttpServletRequest request, HttpServletResponse response) {
        Enumeration<String> attributeNames = request.getAttributeNames();
        while (attributeNames.hasMoreElements()) {
            String element = attributeNames.nextElement();
            LOGGER.info("[success] attributeName: {}", element);
        }

        Map<String, Object> res = new HashMap<>(8);
        res.put("map", request.getAttribute("map"));
        res.put("model", request.getAttribute("model"));
        res.put("request", request.getAttribute("request"));

        Collection<String> headerNames = response.getHeaderNames();
        for (String headerName : headerNames) {
            LOGGER.info("[success] headerName: {}", headerName);
        }


        return res;
    }

    /**
     * 自定义POJO参数类型解析
     *
     * @param book
     * @return
     */
    @ResponseBody
    @GetMapping("/customRequestParameter")
    public Object customRequestParameter(BookEntity book) {
        LOGGER.info("[customRequestParameter] book:{}", book.toString());
        return book;
    }

    /**
     * 响应参数解析
     *
     * @return BookEntity
     */
    @ResponseBody
    @GetMapping("/getBook")
    public BookEntity getBook() {
        BookEntity bookEntity = new BookEntity();
        bookEntity.setId(1L);
        bookEntity.setAuthor("作者");
        bookEntity.setName("书名");
        bookEntity.setPrice(new BigDecimal("12.34"));
        bookEntity.setPublishDate(new Date());

        return bookEntity;
    }

}

